package com.changyue.activity.home;

import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.changyue.activity.basic.BasicActivity;
import com.changyue.bleHelper.BLEConnector;
import com.changyue.bleHelper.Req.BLEReq;
import com.changyue.bleHelper.Req.BLEStartReq;
import com.changyue.bleHelper.Req.BLEStopReq;
import com.changyue.bleHelper.Req.BLETargetTempReq;
import com.changyue.bleHelper.Resp.BLEResp;
import com.changyue.bleHelper.Resp.BLEStartResp;
import com.changyue.bleHelper.Resp.BLEStopResp;
import com.changyue.bleHelper.Resp.BLETargetTempResp;
import com.changyue.bleHelper.ScanActivity;
import com.changyue.activity.me.SettingActivity;
import com.changyue.activity.me.SettingTempActivity;
import com.changyue.bleHelper.BLEDeviceConfig;
import com.changyue.temp.BuildConfig;
import com.changyue.temp.R;
import com.changyue.temp.databinding.ActivityHomeBinding;
import com.changyue.ui.DynamicLineChartManager;
import com.changyue.ui.HeadView;
import com.changyue.ui.MyMarkerView;
import com.changyue.util.CustomToast;
import com.changyue.util.EmptyUtil;
import com.github.mikephil.charting.charts.LineChart;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import cn.com.heaton.blelibrary.ble.Ble;
import cn.com.heaton.blelibrary.ble.BleLog;
import cn.com.heaton.blelibrary.ble.callback.BleNotifyCallback;
import cn.com.heaton.blelibrary.ble.callback.BleWriteCallback;
import cn.com.heaton.blelibrary.ble.model.BleDevice;
import cn.com.heaton.blelibrary.ble.utils.ByteUtils;

public class HomeActivity extends BasicActivity {

    public static String TAG = HomeActivity.class.getName();
    private ActivityHomeBinding binding;
    private Ble<BleDevice> ble = Ble.getInstance();

    private boolean isStart = false;

    private List<Float> list = new ArrayList<>(); //数据集合
    private List<String> names = new ArrayList<>(); //折线名字集合
    private List<Integer> color = new ArrayList<>();//折线颜色集合

    private MyMarkerView mMv;
    private LineChart mChart;
    private DynamicLineChartManager dynamicLineChartManager;
    private Timer timer;

    public static void start(Context context) {
        Intent intent = new Intent(context, HomeActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityHomeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initView();
        loadData();

        EventBus.getDefault().register(this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (isNeedUpdate) {
            isNeedUpdate = false;
            loadData();
        }
    }

    @Subscribe
    public void onEventMainThread(String event) {
        if (event != null) {
            if (event.contains("Setting")) {
                isNeedUpdate = true;
            } else if (event.contains("Scan")) {
                isNeedUpdate = true;
            }
        }
    }

    public void initView() {
        binding.headView.setLeftVisibility(false);
        binding.headView.setRightTxt("设置");
        binding.headView.setRightTxtVisibility(true);
        binding.headView.setOnRightClickListener(new HeadView.OnRightClickListener() {
            @Override
            public void onRightClickListener(View view) {
                SettingActivity.start(HomeActivity.this);
            }
        });

        binding.bleLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ScanActivity.start(HomeActivity.this);
            }
        });

        binding.tempLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SettingTempActivity.start(HomeActivity.this);
            }
        });

        binding.btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isStart) {
                    isStart = true;
                    binding.btnStart.setText(R.string.stop);
                    binding.btnStart.setBackgroundResource(R.drawable.btn_action_red);
                    HomeActivity.this.startTest();
                } else {
                    isStart = false;
                    binding.btnStart.setText(R.string.start);
                    binding.btnStart.setBackgroundResource(R.drawable.btn_action_blue);
                    HomeActivity.this.stopTest();
                }
            }
        });
        initLiner();
    }

    public void initLiner() {
        mMv = new MyMarkerView(this, R.layout.marker_view);
        mChart = (LineChart) binding.lineChart;
        mMv.setChartView(mChart);
        mChart.setMarker(mMv);

        names.add("");
        color.add(Color.RED);

        dynamicLineChartManager = new DynamicLineChartManager(mChart, names, color);
        dynamicLineChartManager.setDescription("X:秒, Y:" + BLEDeviceConfig.temp_unit);
    }

    public void startTest() {
        setTemp(true);
    }

    public void setTemp(boolean isCheckBleAlert) {
        if (EmptyUtil.isEmpty(ble.getConnectedDevices())) {
            if (isCheckBleAlert) {
                CustomToast.middleBottom(HomeActivity.this, "蓝牙断开连接");
            }
            return;
        }

        BleDevice device = ble.getConnectedDevices().get(0);

        Double targetTemp = BLEDeviceConfig.getInstance().targetTemp;
        BLETargetTempReq bleTargetTempReq = new BLETargetTempReq(targetTemp);
        ble.write(device, bleTargetTempReq.getReq(), new BleWriteCallback<BleDevice>() {
            @Override
            public void onWriteSuccess(BleDevice device, BluetoothGattCharacteristic characteristic) {
                Log.e(TAG, "onWriteSuccess: ");
            }

            @Override
            public void onWriteFailed(BleDevice device, int failedCode) {
                Log.e(TAG, "onWiteFailed: " + failedCode);
                HomeActivity.this.handleFail(device, failedCode);
            }
        });
    }

    public void stopTest() {
        sendBleRequest(new BLEStopReq());
    }

    public void loadData() {
        binding.headView.setTitle(BLEDeviceConfig.getInstance().getTypeName());
        binding.targetTemp.setText(BLEDeviceConfig.getInstance().getTargetTempUnit());
        binding.bleName.setText(BLEConnector.getBLEName(ble));
        String deltaStr = "--" + BLEDeviceConfig.temp_unit + "/" + BLEDeviceConfig.getInstance().getPeriod() + BLEDeviceConfig.period_unit;
        binding.delta.setText(deltaStr);
        binding.temp.setText("--");

        if (EmptyUtil.isEmpty(ble.getConnectedDevices())) {
            CustomToast.middleBottom(HomeActivity.this, "蓝牙断开连接");
            return;
        }

        BleDevice device = ble.getConnectedDevices().get(0);

        ble.enableNotify(device, true, new BleNotifyCallback<BleDevice>() {
            @Override
            public void onChanged(BleDevice device, BluetoothGattCharacteristic characteristic) {
                UUID uuid = characteristic.getUuid();
                BleLog.e(TAG, "onChanged==uuid:" + uuid.toString());
                BleLog.e(TAG, "onChanged==data:" + ByteUtils.toHexString(characteristic.getValue()));
                byte[] bytes = characteristic.getValue();
                HomeActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        HomeActivity.this.handleBLEResp(bytes);
                    }
                });
            }

            @Override
            public void onNotifySuccess(BleDevice device) {
                super.onNotifySuccess(device);
                BleLog.e(TAG, "onNotifySuccess");
            }

            @Override
            public void onNotifyFailed(BleDevice device, int failedCode) {
                super.onNotifyFailed(device, failedCode);
                BleLog.e(TAG, "onNotifyFailed " + failedCode);
                HomeActivity.this.handleFail(device, failedCode);
            }

            @Override
            public void onNotifyCanceled(BleDevice device) {
                super.onNotifyCanceled(device);
                BleLog.e(TAG, "onNotifyCanceled");
            }
        });

        startReader();
        if (isStart) {
            setTemp(false);
        }
    }

    public void startReader() {
        binding.temp.setText("0.00");
        String deltaStr = "--" + BLEDeviceConfig.temp_unit + "/" + BLEDeviceConfig.getInstance().getPeriod() + BLEDeviceConfig.period_unit;
        binding.delta.setText(deltaStr);

        dynamicLineChartManager.reset(names, color);
        dynamicLineChartManager = new DynamicLineChartManager(mChart, names, color);

        if (EmptyUtil.isNotEmpty(timer)) {
            timer.cancel();
        }
        timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        sendBleRequest(new BLEStartReq());
                    }
                });
            }
        };
        timer.schedule(task, 0, 1000);
    }


    public void tryToCal() {

        if (!isStart){
            return;
        }

        Integer su = list.size() % BLEDeviceConfig.getInstance().period;
        if (su != 0) {
            return;
        }
        boolean isInit = false;
        int i = list.size() - BLEDeviceConfig.getInstance().period;
        i = i < 0 ? 0 : i;

        Double max = 0.0d;
        Double min = 0.0d;
        for (; i < list.size(); i++) {
            double dt = list.get(i);
            if (!isInit) {
                max = dt;
                min = dt;
                isInit = true;
            }

            if (dt > max) {
                max = dt;
            }
            if (dt < min) {
                min = dt;
            }
        }

        double delta = max - min;
        String deltaStr = BLEDeviceConfig.df.format(delta) + BLEDeviceConfig.temp_unit + "/" + BLEDeviceConfig.getInstance().getPeriod() + BLEDeviceConfig.period_unit;
        binding.delta.setText(deltaStr);
    }

    public void sendBleRequest(BLEReq bleReq) {
        if (EmptyUtil.isEmpty(ble.getConnectedDevices())) {
            CustomToast.middleBottom(HomeActivity.this, "蓝牙断开连接");
            loadData();
            return;
        } else if(BuildConfig.ENV.equalsIgnoreCase("dev")) {
            genBLETestData();
        }

        BleDevice device = ble.getConnectedDevices().get(0);
        ble.write(device, bleReq.getReq(), new BleWriteCallback<BleDevice>() {
            @Override
            public void onWriteSuccess(BleDevice device, BluetoothGattCharacteristic characteristic) {
                Log.e(TAG, "onWriteSuccess: ");
            }

            @Override
            public void onWriteFailed(BleDevice device, int failedCode) {
                Log.e(TAG, "onWiteFailed: " + failedCode);
                HomeActivity.this.handleFail(device, failedCode);
            }
        });
    }

    public void handleFail(BleDevice device, int failedCode) {
        HomeActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                CustomToast.middleBottom(HomeActivity.this, "蓝牙发送消息失败，错误码(" + failedCode + ")");
            }
        });
    }

    public void handleBLEResp(byte[] bytes) {
        BLEResp resp = BLEResp.parse(bytes);
        if (resp instanceof BLEStartResp) {
            BLEStartResp startResp = (BLEStartResp) resp;
            binding.temp.setText(BLEDeviceConfig.getInstance().getFormatData(startResp.temp));
            list.add(startResp.temp);
            tryToCal();
            dynamicLineChartManager.addEntry(startResp.temp);
            binding.lineChart.setDrawMarkers(true);

        } else if (resp instanceof BLEStopResp) {
//            CustomToast.middleBottom(this, "设置成功");
        } else if (resp instanceof BLETargetTempResp) {

        }
    }

    public void genBLETestData() {

        BLEStartResp startResp = new BLEStartResp();
        startResp.temp = (float)Math.round(Math.random()*100.0f);
        binding.temp.setText(BLEDeviceConfig.getInstance().getFormatData(startResp.temp));
        list.add(startResp.temp);
        tryToCal();
        dynamicLineChartManager.addEntry(startResp.temp);
        binding.lineChart.setDrawMarkers(true);

    }

}